package migration

import (
	"apiGateWay/internal/config"
	"apiGateWay/internal/database"
	"apiGateWay/internal/model"
	"apiGateWay/pkg/logger"
	"golang.org/x/crypto/bcrypt"
)

// migrateConfigToDB 将配置文件中的数据迁移到数据库
func MigrateConfigToDB(cfg *config.Config) error {
	if database.DB == nil {
		return nil
	}

	// 迁移路由配置
	if err := migrateRoutes(cfg.Routes); err != nil {
		return err
	}

	// 迁移系统配置
	if err := migrateSystemConfig(cfg); err != nil {
		return err
	}

	// 创建默认管理员用户
	if err := createDefaultAdmin(); err != nil {
		logger.Warnf("创建默认管理员失败: %v", err)
	}

	return nil
}

// migrateRoutes 迁移路由配置
func migrateRoutes(routes []config.RouteConfig) error {
	for _, routeCfg := range routes {
		var route model.Route
		result := database.DB.Where("path = ?", routeCfg.Path).First(&route)
		
		if result.Error != nil {
			// 路由不存在，创建新路由
			route = model.Route{
				Name:         routeCfg.Name,
				Path:         routeCfg.Path,
				Target:       routeCfg.Target,
				Methods:      routeCfg.Methods,
				AuthRequired: routeCfg.AuthRequired,
				IsEnabled:    true,
			}
			if routeCfg.RateLimit.Enabled {
				route.RateLimitQPS = routeCfg.RateLimit.QPS
				route.RateLimitBurst = routeCfg.RateLimit.Burst
			}
			if err := database.DB.Create(&route).Error; err != nil {
				logger.Errorf("创建路由失败: %v", err)
			} else {
				logger.Infof("迁移路由: %s", routeCfg.Path)
			}
		}
	}
	return nil
}

// migrateSystemConfig 迁移系统配置
func migrateSystemConfig(cfg *config.Config) error {
	// 迁移 JWT 配置
	jwtConfig := map[string]interface{}{
		"secret":             cfg.JWT.Secret,
		"issuer":             cfg.JWT.Issuer,
		"expiration":         cfg.JWT.Expiration,
		"refresh_expiration": cfg.JWT.RefreshExpiration,
	}
	
	config := model.SystemConfig{
		Key:      "jwt",
		Category: "auth",
		Value:    jwtConfig,
	}
	database.DB.Save(&config)

	// 迁移限流配置
	rateLimitConfig := map[string]interface{}{
		"enabled":  cfg.RateLimit.Enabled,
		"strategy": cfg.RateLimit.Strategy,
		"global": map[string]interface{}{
			"enabled": cfg.RateLimit.Global.Enabled,
			"qps":     cfg.RateLimit.Global.QPS,
			"burst":   cfg.RateLimit.Global.Burst,
		},
		"per_ip": map[string]interface{}{
			"enabled": cfg.RateLimit.PerIP.Enabled,
			"qps":     cfg.RateLimit.PerIP.QPS,
			"burst":   cfg.RateLimit.PerIP.Burst,
		},
		"per_user": map[string]interface{}{
			"enabled": cfg.RateLimit.PerUser.Enabled,
			"qps":     cfg.RateLimit.PerUser.QPS,
			"burst":   cfg.RateLimit.PerUser.Burst,
		},
	}
	
	config = model.SystemConfig{
		Key:      "rate_limit",
		Category: "rate_limit",
		Value:    rateLimitConfig,
	}
	database.DB.Save(&config)

	return nil
}

// createDefaultAdmin 创建默认管理员用户
func createDefaultAdmin() error {
	var user model.User
	result := database.DB.Where("username = ?", "admin").First(&user)
	
	if result.Error != nil {
		// 用户不存在，创建默认管理员
		hashedPassword, err := bcrypt.GenerateFromPassword([]byte("admin123"), bcrypt.DefaultCost)
		if err != nil {
			return err
		}
		
		user = model.User{
			Username: "admin",
			Password: string(hashedPassword),
			Email:    "admin@example.com",
			IsActive: true,
			IsAdmin:  true,
		}
		
		if err := database.DB.Create(&user).Error; err != nil {
			return err
		}
		logger.Info("创建默认管理员用户: admin")
	}
	return nil
}

